package com.tg.paw.ums.controller;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tg.paw.common.component.UserUtil;
import com.tg.paw.common.util.CommonResult;
import com.tg.paw.ums.dto.LoginDto;
import com.tg.paw.ums.dto.RegisterDto;
import com.tg.paw.ums.dto.UserInfoDto;
import com.tg.paw.ums.entity.Admin;
import com.tg.paw.ums.service.IAdminService;
import com.tg.paw.ums.util.JWTUtil;
import com.tg.paw.ums.util.TokenData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * AdminLoginController
 *
 * @author Rubble
 * @date 2020/6/12
 */
@RestController
@Slf4j
@Api(tags = "用户登录、注册", value = "AdminLoginController")
@RequestMapping("/notAuth")
public class AdminSignController {

    @Value("${jwt.secretKey:123456}")
    private String secretKey;

    @Autowired
    private IAdminService adminService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @ApiOperation(value = "用户登录")
    @PostMapping("/login")
    public CommonResult adminLoginIn(@Valid @RequestBody LoginDto loginDto, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return CommonResult.validateFailed(bindingResult);
        }
        String username = loginDto.getUsername();
        LambdaQueryWrapper<Admin> query = new LambdaQueryWrapper<>();

        if(Validator.isMobile(username)){
            query.eq(Admin::getPhone,username);
        }else if(Validator.isEmail(username)){
            query.eq(Admin::getEmail,username);
        }else {
            query.eq(Admin::getUsername,username);
        }
        Admin admin = adminService.getOne(query);
        if(admin==null){
            return CommonResult.failed("用户名不存在");
        }

        boolean matches = passwordEncoder.matches(loginDto.getPassword(), admin.getPassword());
        if(!matches){
            return CommonResult.failed("密码不正确");
        }

        TokenData tokenData = JWTUtil.generateToken(admin.getUsername(),secretKey);

        return CommonResult.success(tokenData);
    }

    @ApiOperation(value = "刷新token")
    @PostMapping("/refreshToken")
    public CommonResult refreshToken(@RequestParam String token){
        try {
            JWTUtil.verifyToken(token, secretKey);
        }catch (Exception e){
            return CommonResult.failed("无效的token.");
        }
        String username = JWTUtil.getUserInfo(token);
        TokenData tokenData = JWTUtil.generateToken(username,secretKey);
        return CommonResult.success(tokenData);
    }

    @ApiOperation(value = "用户注册")
    @PostMapping("/register")
    public CommonResult adminRegister(@Valid @RequestBody RegisterDto registerDto,BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return CommonResult.validateFailed(bindingResult);
        }
        if(!registerDto.getPassword().equals(registerDto.getConfirmPassword())){
            return CommonResult.failed("确认密码错误");
        }
        Admin entity = new Admin();
        String username = registerDto.getUsername();
        entity.setUsername(username);
        if(Validator.isMobile(username)){
            entity.setPhone(username);
        }
        if(Validator.isEmail(username)){
            entity.setEmail(username);
        }
        Admin admin = adminService.getOne(new QueryWrapper<>(entity));
        if(admin!=null){
            return CommonResult.failed("用户名已存在");
        }

        entity.setPassword(passwordEncoder.encode(registerDto.getPassword()));
        adminService.save(entity);

        return CommonResult.success();
    }

    @ApiOperation(value = "用户登出")
    @PostMapping("/logout")
    public CommonResult logout(){
        return CommonResult.success();
    }

    @ApiOperation(value = "登陆是否需要验证码")
    @PostMapping("/auth/2step-code")
    public CommonResult step2Code(){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("stepCode", false);

        return CommonResult.success(jsonObject);
    }

}
